<template>
  <div class="culture-background-management">
    <div class="card">
      <div class="header">
        <h2>文化背景管理</h2>
        <div class="controls">
          <el-input
            v-model="searchQuery"
            placeholder="请输入文化背景名称"
            style="width: 300px;"
          />
          &nbsp; &nbsp; &nbsp; &nbsp;
          <el-button type="primary" @click="showAddDialog">添加文化背景</el-button>
          <el-button
            type="danger"
            @click="batchDelete"
            :disabled="!selectedDetails.length"
          >
            批量删除
          </el-button>
        </div>
      </div>

      <el-table
        :data="filteredDetails"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        class="culture-table"
        stripe highlight-current-row border 
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="title" label="标题" width="250" align="center"></el-table-column>
        <el-table-column prop="type" label="类型" width="150" align="center"></el-table-column>
        <el-table-column prop="image" label="图片" align="center">
          <template #default="{ row }">
            <el-image
              style="width: 100px; height: 100px"
            :src="'http://localhost:8080/images/upload/' + row.image"/>
          </template>
        </el-table-column>
        <el-table-column prop="view_count" label="浏览次数" width="120" align="center"></el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button @click="editDetail(row)" type="text" size="small">编辑</el-button>
            <el-button @click="viewDetail(row)" type="text" size="small">查看</el-button>
            <el-button
              @click="confirmDelete(row)"
              type="text"
              size="small"
              style="color: red;"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin-top: 20px;"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="details.length"
        @current-change="handlePageChange"
        layout="total, prev, pager, next, jumper"
      />
    </div>

    <!-- 编辑和添加对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑文化背景' : '添加文化背景'" width="700">
      <el-form :model="currentDetail" label-width="80px" ref="detailForm">
        <el-form-item label="标题" prop="title" :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
          <el-input v-model="currentDetail.title"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type" :rules="[{ required: true, message: '请选择类型', trigger: 'change' }]">  
          <el-select v-model="currentDetail.type" placeholder="请选择类型">  
            <el-option label="新国风流行" value="新国风流行"></el-option>  
            <el-option label="传统音乐" value="传统音乐"></el-option>  
            <el-option label="戏曲融合" value="戏曲融合"></el-option>  
            <el-option label="主题文化" value="主题文化"></el-option>  
            <el-option label="地域特色" value="地域特色"></el-option>
          </el-select>  
        </el-form-item> 
        <el-form-item label="描述" prop="description" :rules="[{ required: true, message: '请输入描述', trigger: 'blur' }]">
          <el-input type="textarea" v-model="currentDetail.content" :rows="6"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">  
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/api/instruments/upload"
            :show-file-list="false"
            :on-success="handleSuccess"
          >
            <img v-if="currentDetail.image" :src="'http://localhost:8080/images/upload/'+currentDetail.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveDetail">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="查看文化背景" width="700">
      <el-form :model="currentDetail" label-width="80px" ref="detailForm" :disabled="isView">
        <el-form-item label="标题" prop="title">
          <el-input v-model="currentDetail.title" :disabled="isView"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="currentDetail.type" :disabled="isView">
            <el-option label="新国风流行" value="新国风流行"></el-option>
            <el-option label="传统音乐" value="传统音乐"></el-option>
            <el-option label="戏曲融合" value="戏曲融合"></el-option>
            <el-option label="主题文化" value="主题文化"></el-option>
            <el-option label="地域特色" value="地域特色"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="content">
          <el-input type="textarea" :rows="6" v-model="currentDetail.content" :disabled="isView"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-image
            v-if="currentDetail.image"
            style="width: 100px; height: 100px"
            :src="'http://localhost:8080/images/upload/' + currentDetail.image"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="confirmDeleteDialogVisible" title="确认删除" width="500">
      <span v-if="isBatchDelete">确定要删除所选的文化背景吗？此操作不可撤销。</span>
      <span v-else>确定要删除该文化背景吗？此操作不可撤销。</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="confirmDeleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="performDelete">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { Plus } from '@element-plus/icons-vue'

export default {
  data() {
    return {
      details: [],
      currentDetail: { culture_background_detail_id: '', title: '', type: '', content: '', image: '', view_count: ''},
      dialogVisible: false,
      viewDialogVisible: false, // 控制查看详情对话框显示
      confirmDeleteDialogVisible: false,
      selectedDetails: [],
      isEdit: false,
      isBatchDelete: false, 
      isView: true, // 查看状态
      currentPage: 1,
      pageSize: 10,
      searchQuery: '',
      imageUrl: ""
    };
  },

  computed: {
    filteredDetails() {
      return this.details
        .filter(detail => detail.title.toLowerCase().includes(this.searchQuery.toLowerCase()))
        .slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    },
  },

  methods: {
    handleSuccess(response){
      this.currentDetail.image = response;
    },
    fetchDetails() {
      axios.get('/api/culture-background-detail/all')
        .then(response => {
          this.details = response.data;
        })
        .catch(error => {
          console.error("Error fetching details:", error);
        });
    },
    showAddDialog() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.currentDetail = { culture_background_detail_id: '', title: '', type: '', content: '', image: '', view_count: '' };
    },
    editDetail(detail) {
      this.isEdit = true;
      this.currentDetail = { ...detail };
      this.dialogVisible = true;
    },
    viewDetail(detail) {
      this.isEdit = false;
      this.isView = true; // 设置为只读
      this.currentDetail = { ...detail };
      this.viewDialogVisible = true;
    },

    confirmDelete(detail) {
      this.isBatchDelete = false;
      this.currentDetail = detail;
      this.confirmDeleteDialogVisible = true;
    },
    batchDelete() {
      if (!this.selectedDetails.length) return;
      this.isBatchDelete = true; // 标记为批量删除
      this.confirmDeleteDialogVisible = true;
    },
    performDelete() {
      if (this.isBatchDelete) {
        // 批量删除逻辑
        const idsToDelete = this.selectedDetails.map(detail => detail.culture_background_detail_id);
        const deleteRequests = idsToDelete.map(id =>
          axios.delete(`/api/culture-background-detail/delete/${id}`)
        );

        Promise.all(deleteRequests)
          .then(() => {
            this.details = this.details.filter(detail => !idsToDelete.includes(detail.culture_background_detail_id));
            this.selectedDetails = [];
            this.$message({
              type: 'success',
              message: '批量删除成功！',
            });
          })
          .catch(error => {
            console.error("Error deleting details:", error);
          });
      } else {
        // 单项删除逻辑
        axios.delete(`/api/culture-background-detail/delete/${this.currentDetail.culture_background_detail_id}`)
          .then(() => {
            this.details = this.details.filter(detail => detail.culture_background_detail_id !== this.currentDetail.culture_background_detail_id);
            this.$message({
              type: 'success',
              message: '删除成功！',
            });
          })
          .catch(error => {
            console.error("Error deleting detail:", error);
          });
      }
      this.confirmDeleteDialogVisible = false;
    },
    
    saveDetail() {
      if (this.isEdit) {
        axios.put(`/api/culture-background-detail/update`, this.currentDetail)
          .then(() => {
            const index = this.details.findIndex(detail => detail.culture_background_detail_id === this.currentDetail.culture_background_detail_id);
            if (index !== -1) {
              this.details[index] = { ...this.currentDetail };
            }
            this.dialogVisible = false;
            this.$message({
              type: 'success',
              message: '更新成功！',
            }); 
          })
          .catch(error => {
            console.error("Error updating detail:", error);
          });
      } else {
        axios.post('/api/culture-background-detail/add', this.currentDetail)
          .then(response => {
            this.details.push(response.data);
            this.$message({
              type: 'success',
              message: '添加成功！',
            });
          })
          .catch(error => {
            console.error("Error adding detail:", error);
          });
          this.dialogVisible = false;
      }
    },

    handleSelectionChange(selected) {
      this.selectedDetails = selected;
    },

    handlePageChange(page) {
      this.currentPage = page;
    }
  },

  mounted() {
    this.fetchDetails();
  },
};
</script>

<style scoped>
.culture-background-management {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.card {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.controls {
  display: flex;
  align-items: center;
}

.controls el-input {
  margin-right: 20px;
}

.culture-table {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  background-color: #ffffff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
